package com.itxiuyixiu.tools.security.user;


import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author 黄磊
 * @date 2020/1/26
 */
public class GetUser {
    public static String getUserName() throws UserNotFoundException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new UserNotFoundException("用户未登录，请先登录");
        }
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        return userDetails.getUsername();
    }

    public static UserDetails getUserDetails() throws UserNotFoundException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new UserNotFoundException("用户未登录，请先登录");
        }
        return (UserDetails) authentication.getPrincipal();
    }
}
